import { useState, useEffect } from "react";
import { useParams } from 'react-router-dom'
import './cart.scss'
import axios from 'axios'
import Delete from "./delete_sure/delete";

export default function Cart() {
    var params = useParams()
    var [checkAll, setCheckAll] = useState(false)
    let [cartList, setCartList] = useState([])
    let [shopnum, setshopnum] = useState()
    let [numAll, setnumAll] = useState()
    let [numFilter, setnumFilter] = useState()
    let [shopPrice, setshopPrice] = useState()
    let [delshow, setdelshow] = useState(false)
    var token = JSON.parse(localStorage.userInfor).token
    useEffect(() => {
        getshopCart()
    }, [])
    // 调购物车接口
    function getshopCart() {
        axios({
            method: 'GET',
            url: 'https://apipc-xiaotuxian-front.itheima.net/member/cart',
            headers: {
                Authorization: 'Bearer ' + token
            },
        }).then(res => {
            if (res.data.msg == '操作成功') {
                cartList = res.data.result

                // 全选
                let bool = true
                res.data.result.forEach(i => {
                    if (i.selected == false) {
                        bool = false
                    }
                })
                setCartList(cartList)
                setCheckAll(bool)

                getnumAll()  // 总数量
                getnumFilter()  // 选中数量
                getshopPrice()  // 选中的总价
            }
        })
    }
    // 商品数量的input框 onChange事件  
    function numchange() {
        cartList.forEach(item => {
            setshopnum(item.count)
        })
    }
    // 全选
    function checkAllchange() {
        let ids = []
        cartList.forEach(i => {
            if (i.isEffective) {
                ids.push(i.skuId)
            }
        })
        console.log(ids);
        axios({
            method: 'PUT',
            url: 'https://apipc-xiaotuxian-front.itheima.net/member/cart/selected',
            data: {
                ids: ids,
                selected: !checkAll,
            },
            headers: {
                Authorization: 'Bearer ' + token
            },
        }).then(res => {
            if (res.data.msg == '操作成功') {
                getshopCart()
            }
        })
    }
    // 反选
    function selectOne(item) {
        item.selected = !item.selected
        axios.put('https://apipc-xiaotuxian-front.itheima.net/member/cart/' + item.skuId,
            { selected: item.selected },
            { headers: { 'Authorization': 'Bearer ' + token } }
        ).then(res => {
            if (res.data.msg == '操作成功') {
                let bool = true
                cartList.forEach(i => {
                    if (i.selected == false) {
                        bool = false
                    }
                })
                setCheckAll(bool)
                getshopCart()
            }
            if (res.data.msg != '操作成功') {
                getshopCart()
            }
        })
    }
    // 数量-
    function subtract(item) {
        if (item.count > 1) {
            axios({
                method: 'PUT',
                url: 'https://apipc-xiaotuxian-front.itheima.net/member/cart/' + item.skuId,
                data: {
                    count: item.count - 1
                },
                headers: {
                    Authorization: 'Bearer ' + token
                }
            }).then(res => {
                getshopCart()
            })
        }

    }
    // 加数量
    function addNum(item) {
        axios({
            method: 'PUT',
            url: 'https://apipc-xiaotuxian-front.itheima.net/member/cart/' + item.skuId,
            data: {
                count: item.count + 1
            },
            headers: {
                Authorization: 'Bearer ' + token
            }
        }).then(res => {
            getshopCart()
        })
    }
    // 商品总数量
    function getnumAll() {
        let num = 0
        cartList.forEach(item => {
            if (item.isEffective) {
                num += item.count
            }
        })
        setnumAll(num)
    }
    // 选中商品数量
    function getnumFilter() {
        let num = 0
        cartList.forEach(item => {
            if (item.isEffective && item.selected) {
                num += item.count
            }
        })
        setnumFilter(num)
    }
    // 选中商品的总价
    function getshopPrice() {
        let sum = 0
        cartList.forEach(item => {
            if (item.isEffective && item.selected) {
                sum += Number(item.price) * item.count
            }
        })
        setshopPrice(sum)
    }
    // 删除商品弹窗
    function popup() {
        setdelshow(true)
    }
    // 删除
    function del(item) {
        var ids = [item.skuId]
        axios({
            method: 'DELETE',
            url: 'https://apipc-xiaotuxian-front.itheima.net/member/cart',
            data: {
                ids: ids
            },
            headers: {
                Authorization: 'Bearer ' + token
            }
        }).then(res => {
            getshopCart()
        })
    }
    // 删除选中
    function delchecked(e) {
        e.preventDefault()
        var ids = [];
        cartList.forEach(i => {
            if (i.selected == true) {
                ids.push(i.skuId)
            }
        })
        axios({
            method: 'DELETE',
            url: 'https://apipc-xiaotuxian-front.itheima.net/member/cart',
            data: {
                ids: ids
            },
            headers: {
                Authorization: 'Bearer ' + token
            }
        }).then(res => {
            getshopCart()
        })
    }
    return (
        <div id="cartwrap">
            <div className="container">
                <div id="navigation">
                    <div className="container">
                        <a href="">首页</a>
                        <i> &gt; </i>
                        <a href="">购物车</a>
                    </div>
                </div>
                <div className="cart">
                    <table>
                        <thead>
                            <tr>
                                <th width="120">
                                    <input type="checkbox" checked={checkAll} onChange={checkAllchange} />
                                    <span>全选</span>
                                </th>
                                <th width="400">商品信息</th>
                                <th width="220">单价</th>
                                <th width="180"> 数量</th>
                                <th width="180">小计</th>
                                <th width="140">操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            {(cartList.filter((i) => { return i.isEffective == true })).map((item, index) => {
                                return (
                                    <tr key={index}>
                                        <td><input type="checkbox" checked={item.selected} onChange={selectOne.bind(this, item)} /></td>
                                        <td>
                                            <div className="goods">
                                                <img src={item.picture} alt="" />
                                                <div>
                                                    <p>{item.name}</p>
                                                    <div className="cart_skus">
                                                        <div className="attrs">
                                                            <span>{item.attrsText}</span>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </td>
                                        <td>
                                            <p>￥{item.price}</p>
                                        </td>
                                        <td>
                                            <div className="numbox">
                                                <span onClick={subtract.bind(this, item)}>-</span>
                                                <input type="text" value={item.count} onChange={numchange} />
                                                <span onClick={addNum.bind(this, item)}>+</span>
                                            </div>
                                        </td>
                                        <td>
                                            <p style={{ fontSize: '16px', color: '#cf4444' }}>￥{(item.nowOriginalPrice * item.count).toFixed(2)}</p>
                                        </td>
                                        <td>
                                            <p style={{ cursor: 'pointer', userSelect: 'none' }}>移入收藏夹</p>
                                            <p style={{ color: '#27ba9b', cursor: 'pointer', userSelect: 'none' }} onClick={popup.bind(this) && del.bind(this, item)}>删除
                                            </p>
                                            <p style={{ cursor: 'pointer', userSelect: 'none' }}>找相似</p>
                                        </td>
                                        {/* {delshow && <Delete item={item} delshow={delshow}></Delete>} */}

                                    </tr>
                                )
                            })}
                        </tbody>
                        {cartList.filter((i) => { return i.isEffective == false }).length > 0 && (
                            <tbody>
                                <tr>
                                    <td>
                                        <h3>失效商品</h3>
                                    </td>
                                </tr>
                                {(cartList.filter((i) => { return i.isEffective == false })).map((item, index) => {
                                    return (
                                        <tr key={item.id}>
                                            <td><input type="checkbox" /></td>
                                            <td>
                                                <div className="goods">
                                                    <img src={item.picture} alt="" />
                                                    <div>
                                                        <p>{item.name}</p>
                                                        <div className="cart_skus">
                                                            <div className="attrs">
                                                                <span>{item.attrsText}</span>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </td>
                                            <td>
                                                <p>￥{item.price}</p>
                                            </td>
                                            <td>
                                                <div className="numbox">
                                                    <span >-</span>
                                                    <input type="text" />
                                                    <span >+</span>
                                                </div>
                                            </td>
                                            <td>
                                                <p style={{ fontSize: '16px', color: '#cf4444' }}>￥{item.nowOriginalPrice * item.count}</p>
                                            </td>
                                            <td>
                                                <p style={{ cursor: 'pointer', userSelect: 'none' }}>移入收藏夹</p>
                                                <p style={{ color: '#27ba9b', cursor: 'pointer', userSelect: 'none' }} >删除
                                                </p>
                                                <p style={{ cursor: 'pointer', userSelect: 'none' }}>找相似</p>
                                            </td>
                                        </tr>
                                    )
                                })}
                            </tbody>
                        )}


                    </table>
                </div >
                <div className="action">
                    <div className="batch" style={{ display: 'flex' }}>
                        <div className="ckall">
                            <input type="checkbox" checked={checkAll} onChange={checkAllchange} />
                            <span>全选</span>
                        </div>
                        <a href="" onClick={delchecked.bind(this)}>删除商品</a>
                        <a href="">移入收藏夹</a>
                        <a href="">清空失效商品</a>
                    </div>
                    <div className="total">
                        <p>共
                            <span>{numAll}</span>
                            件商品，已选择
                            <span>{numFilter}</span>
                            件，商品合计：
                            <span className="priceAll">￥{shopPrice}</span>
                        </p>
                        <button>下单结算</button>
                    </div>
                </div >
            </div >
        </div >
    )
}